package com.seuic.hid_demo.service

import android.app.Service
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.IBinder
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.BusUtils
import com.blankj.utilcode.util.SPUtils
import com.seuic.dongwuinternetmanager.util.yes
import com.seuic.hid_demo.Constans
import com.seuic.hid_demo.bean.HidReport
import com.seuic.hid_demo.util.ext.hidManager
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.nio.charset.Charset
import java.util.*
import java.util.concurrent.ConcurrentLinkedQueue


/**
 * @author KP
 * @Desc
 * @date 2020/12/17 9:39
 */
class HidService : LifecycleService() {

    private val scannerIntentFilter by lazy {
        IntentFilter().apply {
            //注册广播接收器
            addAction(Constans.SCANACTION)
            priority = 1000
        }
    }
    private val bluetoothIntentFilter by lazy {
        IntentFilter().apply {
            addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
            addAction(BluetoothDevice.ACTION_FOUND)
            addAction(BluetoothDevice.ACTION_PAIRING_REQUEST)
            addAction(BluetoothDevice.ACTION_ACL_CONNECTED)

            priority = 1000
        }
    }
    private val bluetoothReceiver by lazy {
        object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                val action = intent!!.action
                try {
                    when (action) {
                        BluetoothDevice.ACTION_FOUND -> {
                        }
                        "android.bluetooth.device.action.PAIRING_REQUEST" -> {
                        }
                        BluetoothDevice.ACTION_BOND_STATE_CHANGED, BluetoothDevice.ACTION_ACL_CONNECTED -> {
                            val state = intent.getIntExtra(
                                BluetoothAdapter.EXTRA_CONNECTION_STATE,
                                BluetoothAdapter.STATE_CONNECTED
                            )
                            if (state == BluetoothAdapter.STATE_CONNECTED) {
                                val device: BluetoothDevice =
                                    intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                                hidManager.connectDevice(device)
                            }
                        }
                    }
                } catch (ex: Exception) {
                    ex.printStackTrace()
                }
            }
        }
    }

    private val scannerReceiver by lazy {
        object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                if (intent?.action != null && intent.action == Constans.SCANACTION) {
                    val code = intent.getStringExtra("scannerdata")
                    BusUtils.postSticky(Constans.EVENT_TAG_SCAN, code)
                    SPUtils.getInstance().getBoolean(Constans.autoSendKey, false).yes {
                        if (!code.isNullOrBlank() && hidManager.isConnected) {
                            SPUtils.getInstance()
                                .getString(Constans.encodingKey, Constans.encodings[0])
                                .also {
                                    when (Constans.encodings.indexOfFirst { s -> s == it }) {
                                        0 -> hidManager.sendText(
                                            code,
                                            Charset.defaultCharset(),
                                            true
                                        )
                                        1 -> hidManager.sendText(code, Charset.forName("GBK"))
                                        2 -> hidManager.sendText(code, Charsets.UTF_8)
                                    }
                                }
                        }
                    }
                }
            }
        }
    }


    override fun onCreate() {
        super.onCreate()
        BusUtils.register(this)
        registerReceiver(scannerReceiver, scannerIntentFilter)
        registerReceiver(bluetoothReceiver, bluetoothIntentFilter)
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)
        val intent = Intent("com.android.scanner.service_settings")
        intent.putExtra(
            "action_barcode_broadcast",
            Constans.SCANACTION
        )
        sendBroadcast(intent)
        return Service.START_STICKY_COMPATIBILITY
    }

    override fun onBind(intent: Intent): IBinder? {
        super.onBind(intent)
        return null
    }


    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(bluetoothReceiver)
        unregisterReceiver(scannerReceiver)
        BusUtils.unregister(this)
    }
}